#include <iostream>
#include <string>
#include "audio.h"
#include "core.h"

#include "irrKlang.h"

namespace {
    irrklang::ISoundEngine* engine;
    const int MAX_SOUNDS = 100;
    irrklang::ISoundSource *sounds[MAX_SOUNDS];
    int sp = 0;
    std::string path;

    const int MAX_MUSICS = 10;
    int mp = 0;
    irrklang::ISoundSource *musics[MAX_MUSICS];
    irrklang::ISound *music_isound = 0;
    
}  // namespace

namespace audio {
    void Init(const std::string &resource_path) {
        CHECK(engine = irrklang::createIrrKlangDevice());
        path = resource_path;
    }
    
    SoundId LoadSound(const std::string &name) {
        SoundId id = sp++;
        sounds[id] = engine->addSoundSourceFromFile((path + "/" + name).c_str());
        return id;
    }

    void PlaySound(SoundId sound_id, float volume) {
        sounds[sound_id]->setDefaultVolume(volume);
        engine->play2D(sounds[sound_id], false);
    }

    MusicId LoadMusic(const std::string &name) {
        MusicId id = mp++;
        musics[id] = engine->addSoundSourceFromFile((path + "/" + name).c_str());
        return id;
    }

    void PlayMusic(MusicId music_id) {
        StopMusic();
        CHECK(music_isound = engine->play2D(musics[music_id], true, false, true));
    }
    void StopMusic() {
        if (!music_isound) return;
        music_isound->stop();
        music_isound->drop();
        music_isound = 0;
    }
}
